<template>
  <div>
    <header>
      <div class="headerImg">
        <div style="width:80%; margin: 20px auto 0 auto;">
          <img style="width: 100%;" src="@/assets/bg_logo.png">
        </div>
        
      </div>
    </header>
    <cube-form
      :model="model"
      :schema="schema"
      @submit="submitHandler"
    ></cube-form>   

    <div class="copy-right"><p>Copyright © 2020 广州联外教育科技发展中心版权所有 <br/><a href="http://www.miitbeian.gov.cn" target="_blank">粤ICP备17036494号-1</a></p></div>

  </div>
</template>

<script>
import { login } from "../api/user";
import { initWebSocket, close } from "../utils/websocket";

export default {
  name: "Login",
  data() {
    return {
      model: {
        username: "",
        password: ""
      },
      schema: {
        fields: [
          {
            type: "input",
            modelKey: "username",
            label: "账号",
            props: {
              placeholder: "请输入账号"
            },
            rules: {
              required: true,
              type: "string",
              min: 3,
              max: 20
            },
            trigger: "blur",
            message: {
              required: "请输入账号",
              min: "账号不能少于三个字符",
              max: "账号不能大于20个字符"
            }
          },
          {
            type: "input",
            modelKey: "password",
            label: "密码",
            props: {
              placeholder: "请输入密码",
              type: "password",
              eye: { open: false }
            },
            rules: {
              required: true
            },
            trigger: "blur",
            message: {
              required: "请输入密码"
            }
          },
          {
            // 自动识别注册按钮
            type: "submit",
            label: "登录"
          }
        ]
      }
    };
  },
  created() {
    this.$store.commit("setToken", "");
    localStorage.clear();
    close();
  },
  methods: {
    submitHandler(e) {
      e.preventDefault();
      login(this.model)
        .then(response => {
          console.log(response);
          if (response && response.errCode === 0) {
            this.$store.commit("setToken", response.data.token);
            localStorage.setItem("currentUser", JSON.stringify(response.data));
            localStorage.setItem("ws", response.data.host);
            initWebSocket();
            // 判断路由是否带有参数
            if (this.$route.query.redirect) {
              this.$router.replace(this.$route.query.redirect);
            } else {
              this.$router.replace("botnav/index");
            }
          }
        })
        .catch(error => {
          this.$toastErrorCode(error);
        });
    }
  }
};
</script>

<style lang="stylus" scoped>
.headerImg {
  width: 100%;
  height: calc((100vw * 10 / 16));
  background-color: #fff;
}

.copy-right {
  width: 100%;
  text-align: center;
  font-size: 12px;
  line-height: 16px;
  color: #999;
  margin: 0 auto;
  bottom: 5px;
  position :absolute;
}
</style>
